#include "stdafx.h"
#include "ASN1Encodable.h"
#include "ASN1Integer.h"

namespace AppliedCryptography
{
	ASN1Encodable::ASN1Encodable()
		: ASN1Type(Universal, Primitive, EOC)
	{
	};

	ASN1Encodable::ASN1Encodable(ASN1Type& type)
		: ASN1Type(type)
	{
	};

	ASN1Encodable::ASN1Encodable(ClassBits classBits, ConstructedBit constucted, TypeNumberBits number)
		: ASN1Type(classBits, constucted, number)
	{
	};

	std::vector<byte> ASN1Encodable::getLengthBits() const
	{
		std::vector<byte> buffer;
		ASN1Integer lenVal(this->getContentBits().size());

		buffer =  lenVal.getContentBits();

		if(buffer.size() > 1 || buffer[0] & 0x80)
		{
			// First byte contains number of bytes used for len
			int val = buffer.size() | 0x80;
			buffer.insert(buffer.begin(), val);
		};

		return buffer;
	};

	std::vector<byte> ASN1Encodable::encode() const
	{
		std::vector<byte> buffer;

		byte classBits;
		std::vector<byte> lengthBits;
		std::vector<byte> valueBits;

		classBits = this->getTypeBits();
		valueBits = this->getContentBits();

		//lengthBits = this->getLengthBits();
		ASN1Integer lenVal(valueBits.size());
		lengthBits =  lenVal.getContentBits();
		if(lengthBits.size() > 1 || lengthBits[0] & 0x80)
		{
			// First byte contains number of bytes used for len
			int val = lengthBits.size() | 0x80;
			lengthBits.insert(lengthBits.begin(), val);
		};


		buffer.push_back(classBits);
		buffer.insert(buffer.end(), lengthBits.begin(), lengthBits.end());
		buffer.insert(buffer.end(), valueBits.begin(), valueBits.end());

		return buffer;
	};
}; // namespace AppliedCryptography


